from fastapi import APIRouter, HTTPException, Request
from typing import List, Any
import json
import os

router = APIRouter()

# 导入需求分析器
try:
    from app.core.requirement_analyzer import RequirementAnalyzer
    ANALYZER = None  # 延迟初始化
except Exception as e:
    ANALYZER = None
    print(f"RequirementAnalyzer 导入失败: {e}")


@router.post('/analyze-requirements')
async def analyze_requirements(request: Request):
    """
    需求分析接口：优先使用仓库内的工作流/模型（如果可用），否则回退到关键词规则。
    返回结构：{ suggestedComponents: [...], analysis: {...} }
    """
    try:
        global ANALYZER
        body = await request.json()
        desc = body.get('description', '') if isinstance(body, dict) else ''
        framework = body.get('uiFramework', 'react')
        language = body.get('language', 'typescript')
        build_tool = body.get('buildTool', 'vite')
        target_platform = body.get('targetPlatform', 'web')
        exclude_components = body.get('excludeComponents', [])  # 需要排除的组件

        suggested = []
        used_model = False
        model_error = None

        # 初始化分析器
        if ANALYZER is None and 'RequirementAnalyzer' in globals():
            try:
                ANALYZER = RequirementAnalyzer()
            except Exception as e:
                ANALYZER = None
                model_error = str(e)

        # 使用模型分析
        if ANALYZER and desc.strip():
            try:
                result = ANALYZER.analyze_requirements(desc, framework, language, build_tool, target_platform, exclude_components)
                if result.get('success') and result.get('data', {}).get('components'):
                    suggested.extend(result['data']['components'])
                    used_model = True
            except Exception as e:
                model_error = str(e)

        # 关键词回退规则（如果模型分析失败或没有返回结果）
        if not suggested:
            # 根据框架定义不同的组件推荐
            if framework == 'react':
                keywords_map = [
                    (['上传', '上传文件', '文件', 'upload'], [{'name': 'react-dropzone', 'description': '文件上传组件', 'required': False, 'version': '^14.0.0'}]),
                    (['编辑', '富文本', '编辑器', 'editor'], [{'name': 'react-quill', 'description': 'React 富文本编辑器', 'required': False, 'version': '^2.0.0'}]),
                    (['图表', '可视化', 'chart', '统计'], [{'name': 'recharts', 'description': 'React 图表库', 'required': False, 'version': '^2.8.0'}]),
                    (['表单', 'form', '验证'], [{'name': 'react-hook-form', 'description': 'React 表单管理', 'required': False, 'version': '^7.45.0'}]),
                ]
            elif framework == 'vue':
                keywords_map = [
                    (['上传', '上传文件', '文件', 'upload'], [{'name': 'vue-upload-component', 'description': 'Vue 文件上传组件', 'required': False, 'version': '^3.1.0'}]),
                    (['编辑', '富文本', '编辑器', 'editor'], [{'name': 'vue-quill-editor', 'description': 'Vue 富文本编辑器', 'required': False, 'version': '^1.0.0'}]),
                    (['图表', '可视化', 'chart', '统计'], [{'name': 'vue-echarts', 'description': 'Vue ECharts 组件', 'required': False, 'version': '^6.6.0'}]),
                ]
            else:  # 其他框架
                keywords_map = []
            
            # 通用组件（适用于所有框架）
            universal_keywords = [
                (['OCR', '识别', 'ocr'], [{'name': 'tesseract.js', 'description': '浏览器端 OCR', 'required': False, 'version': '^2.0.0'}]),
                (['时间', '日期', 'date', 'time'], [{'name': 'dayjs', 'description': '轻量级日期处理库', 'required': False, 'version': '^1.11.0'}]),
                (['工具', 'utils', 'lodash'], [{'name': 'lodash', 'description': '实用工具函数库', 'required': False, 'version': '^4.17.0'}]),
            ]
            
            keywords_map.extend(universal_keywords)

            if desc:
                for keys, comps in keywords_map:
                    for k in keys:
                        if k in desc:
                            # 过滤掉已在基础组件中的包
                            filtered_comps = [comp for comp in comps if comp['name'] not in exclude_components]
                            suggested.extend(filtered_comps)
                            break

            # 如果仍无匹配，则给出与框架相关的通用建议（避免前端看到空列表）
            if not suggested:
                if framework == 'react':
                    defaults = [
                        {'name': 'axios', 'description': 'HTTP 请求库', 'required': False, 'version': '^1.7.2'},
                        {'name': 'react-hook-form', 'description': 'React 表单管理', 'required': False, 'version': '^7.45.0'},
                        {'name': 'recharts', 'description': 'React 图表库', 'required': False, 'version': '^2.8.0'},
                    ]
                elif framework == 'vue':
                    defaults = [
                        {'name': 'axios', 'description': 'HTTP 请求库', 'required': False, 'version': '^1.7.2'},
                        {'name': 'vee-validate', 'description': 'Vue 表单校验', 'required': False, 'version': '^4.12.0'},
                        {'name': 'vue-echarts', 'description': 'Vue ECharts 组件', 'required': False, 'version': '^6.6.0'},
                    ]
                else:
                    defaults = [
                        {'name': 'axios', 'description': 'HTTP 请求库', 'required': False, 'version': '^1.7.2'}
                    ]

                suggested.extend([comp for comp in defaults if comp['name'] not in exclude_components])
        
        # 最终过滤：确保推荐的组件不在排除列表中
        suggested = [comp for comp in suggested if comp.get('name') not in exclude_components]

        return {
            'suggestedComponents': suggested,
            'usedModel': used_model,
            'modelError': model_error,
            'fallbackUsed': not used_model and len(suggested) > 0
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post('/generate-directory-structure')
async def generate_directory_structure(request: Request):
    try:
        global ANALYZER
        body = await request.json()

        project_name = body.get('projectName', '')
        framework = body.get('uiFramework', 'react')
        language = body.get('language', 'typescript')
        build_tool = body.get('buildTool', 'vite')
        target_platform = body.get('targetPlatform', 'web')
        description = body.get('description', '')

        def normalize_components(raw: Any) -> List[str]:
            result: List[str] = []
            if isinstance(raw, list):
                for item in raw:
                    if isinstance(item, str):
                        result.append(item)
                    elif isinstance(item, dict):
                        name = item.get('name') or item.get('label') or ''
                        if name:
                            result.append(name)
            return result

        base_components = normalize_components(body.get('baseComponents', []))
        extended_components = normalize_components(body.get('extendedComponents', []))

        if ANALYZER is None and 'RequirementAnalyzer' in globals():
            try:
                ANALYZER = RequirementAnalyzer()
            except Exception as e:
                ANALYZER = None
                raise HTTPException(status_code=500, detail=f"初始化需求分析器失败: {e}")

        if ANALYZER is None:
            raise HTTPException(status_code=500, detail='分析器不可用，无法生成目录结构')

        result = ANALYZER.generate_directory_structure(
            project_name=project_name,
            framework=framework,
            language=language,
            build_tool=build_tool,
            target_platform=target_platform,
            base_components=base_components,
            extended_components=extended_components,
            description=description,
        )

        return result
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
